package models

import (
	"3rd/errors"
	"bytes"
	"encoding/json"
	"github.com/astaxie/beego/validation"
	"strconv"
			goerrors "github.com/go-errors/errors"
)

func ParseBody(body []byte, obj interface{}) error {
	return goerrors.New(json.Unmarshal(body, obj))
}

func Validate(obj interface{}) error {
	valid := validation.Validation{}
	b, err := valid.Valid(obj)
	if err != nil {
		return goerrors.New(err)
	}
	if !b {
		var buffer bytes.Buffer
		for _, err := range valid.Errors {
			buffer.WriteString(err.Field + " " + err.String() + ";")
			if code, ex := strconv.Atoi(err.Key); ex == nil {
				return errors.New(code, buffer.String())
			}
		}
		return errors.New(ParseError, buffer.String())
	}
	return nil
}

func ParseBodyAndValidate(body []byte, obj interface{}) error {
	if err := json.Unmarshal(body, obj); err != nil {
		return goerrors.New(err)
	}
	return Validate(obj)
}

// TODO:
//func init() {
//	goerrors.MaxStackDepth = 5
//}
